package com.shuadianji

import android.os.Bundle
import android.provider.Settings
import android.provider.Settings.SettingNotFoundException
import android.support.v7.app.AppCompatActivity
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import java.net.NetworkInterface
import java.net.SocketException



class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val  s =getLocalIpAddress()

        if(s==null){
            tvIp.text="null"
        }else{
            tvIp.text=s
        }
    }

    fun getLocalIpAddress(): String? {
        val en = NetworkInterface.getNetworkInterfaces()
        try {
            while (en.hasMoreElements()) {
                val intf = en.nextElement()
                val enumIpAddr = intf.inetAddresses
                while (enumIpAddr.hasMoreElements()) {
                    val inetAddress = enumIpAddr.nextElement()
                    if (!inetAddress.isLoopbackAddress) {
                        return inetAddress.hostAddress.toString()
                    }
                }
            }
        } catch (ex: SocketException) {
            ex.printStackTrace()
            Log.d("TAAG",ex.toString())
        }
        return null
    }
    fun gai(){
        val cr = this.contentResolver
        try {
            if (Settings.System.getInt(cr, Settings.System.WIFI_USE_STATIC_IP) === 0) {
                Log.d("Demo", "No use Static IP!")
            } else {
                Log.d("Demo", "use Static IP and Change IP to 192.168.1.123!")
                Settings.System.putString(cr, Settings.System.WIFI_STATIC_IP, "192.168.1.125")
                Settings.System.putString(cr, Settings.System.WIFI_STATIC_GATEWAY, "192.168.1.1")
                Settings.System.putString(cr, Settings.System.WIFI_STATIC_NETMASK, "255.255.255.0")
                Settings.System.putString(cr, Settings.System.WIFI_STATIC_DNS1, "202.103.24.68")
                Settings.System.putString(cr, Settings.System.WIFI_STATIC_DNS2, "202.103.0.68")
            }
        } catch (e: SettingNotFoundException) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        }

    }
}
